package com.creditease.rss.ui;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorCompletionService;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.Display;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnCreateContextMenuListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

import com.creditease.rss.RssConst;
import com.creditease.rss.dao.RssDB;
import com.creditease.rss.dao.RssItemDB;
import com.creditease.rss.model.RssItemModel;
import com.creditease.rss.model.RssModel;
import com.creditease.rss.services.FeedServices;
import com.creditease.rss.ui.adapter.RssAdapter;
import com.creditease.rss.util.ExceptionUtil;
import com.creditease.rss.util.LogUtil;
import com.creditease.rss.util.NetUtil;
import com.creditease.rss.util.PicDownloadUtil;

import de.nava.informa.core.ParseException;

public class HomeActivity extends Activity {
	private final static String TAG = HomeActivity.class.getName();
	private FeedServices feedServices;
	private ListView gridView;
	private RssDB db;
	private RssItemDB itemDb;
	private TextView titleText;
	private EditText addRssEditText;
	private Handler handler;
	private ProgressDialog mpDialog;
	private ImageView reflushView;
	private static final int MSG_SUCCESS = 0;//
	private static final int MSG_FAILURE = 1;//
	private static final int ADD_SUCCESS = 2;//
	private static final int ADD_FAILURE = 3;//
	private static final int MODEL_SUCCESS = 4;//
	private ProgressBar progressBar;
	private RssAdapter adapter;
	private List<RssModel> rssList;
	public static int screenWidth;
	public static int screenHeight;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_CUSTOM_TITLE);
		setContentView(R.layout.home);
		getWindow().setFeatureInt(Window.FEATURE_CUSTOM_TITLE, R.layout.title);
		feedServices = new FeedServices(getApplicationContext());

		
		WindowManager windowManager = getWindowManager();
		Display display = windowManager.getDefaultDisplay();
		screenWidth = display.getWidth();
		screenHeight = display.getHeight();
		// 初始化图片下载
		PicDownloadUtil.init(screenWidth, screenHeight);

		db = new RssDB(getApplicationContext());
		itemDb = new RssItemDB(getApplicationContext());
		rssList = loadData();
		adapter = new RssAdapter(getApplicationContext(), rssList);
		// 标题
		titleText = (TextView) findViewById(R.id.titleText);
		titleText.setText(R.string.app_name);
		// 获得GridView实例
		gridView = (ListView) findViewById(R.id.gridView);

		// 将GridView和数据适配器关联
		gridView.setAdapter(adapter);
		reflushView = (ImageView) findViewById(R.id.reflushIcon);
		progressBar = (ProgressBar) findViewById(R.id.progressbar);
		// 给刷新按钮 添加刷新事件
		reflushView.setOnClickListener(new ReflushClickListener());
		handler = new Handler() {
			@Override
			public void handleMessage(Message msg) {

				switch (msg.what) {
				case MSG_SUCCESS:// 将进度条可见
					reflushRss();
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), "刷新成功", Toast.LENGTH_LONG).show();
					break;
				case ADD_SUCCESS:
					reflushRss();
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), "添加RSS成功", Toast.LENGTH_LONG).show();
					break;
				case ADD_FAILURE:
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), R.string.rssUrlValid, Toast.LENGTH_LONG)
							.show();
					break;
				default:
					reflushRss();
					progressBar.setVisibility(View.INVISIBLE);
					Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_LONG)
							.show();
				}
			}
		};
		// 事件监听
		gridView.setOnItemClickListener(new OnItemClickListener() {
			public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
				final RssModel item = (RssModel) parent.getItemAtPosition(position);
				String url = item.url;
				String idStr = item.id;
				String title = item.title;
				final Intent intent = new Intent();
				intent.setClass(HomeActivity.this, ListRssActivity.class);
				intent.putExtra("title", title);
				intent.putExtra("url", url);
				intent.putExtra("id", idStr);
				// 刷新
				List<RssItemModel> items = itemDb.findByPart(idStr, 0, 1);
				if (!idStr.equals("1") && (items == null || items.isEmpty())) {
					if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
						Toast.makeText(getApplicationContext(), R.string.neterr, Toast.LENGTH_LONG)
								.show();
						return;
					}
					final ProgressDialog dialog = showDailog();
					// dialog.show();
					final String fidString = idStr;
					// 首次加载数据
					Thread refrushThread = new Thread(new Runnable() {
						@Override
						public void run() {
							Looper.prepare();
							try {
								feedServices.refrush(fidString);
								// RssModel model=db.findById(fidString);
								// 设置为 已读
								if (!item.isRead) {
									item.isRead = true;
									db.updateById(item);
								}
								startActivity(intent);
							}
							catch (Exception e) {
								Toast.makeText(	getApplicationContext(),
												R.string.loadingErr,
												Toast.LENGTH_LONG).show();
							}
							finally {
								dialog.cancel();
							}
							Looper.loop();
						}
					});
					// handler.post(refrushThread);
					refrushThread.start();
				} else {
					// 设置为 已读
					if (!item.isRead) {
						item.isRead = true;
						db.updateById(item);
					}
					startActivity(intent);
				}
			}
		});
		gridView.setOnCreateContextMenuListener(new OnCreateContextMenuListener() {
			@Override
			public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
				menu.setHeaderTitle(R.string.homeGridmenu);
				menu.add(1, 1, 1, R.string.rssDel);
				menu.add(1, 2, 2, R.string.rssEmpty);
				menu.add(1, 3, 3, R.string.btnCancel);
			}
		});
		gridView.setOnItemLongClickListener(new OnItemLongClickListener() {
			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
				RssModel item = (RssModel) parent.getItemAtPosition(position);
				String url = item.url;
				String idStr = item.id;
				delId = Integer.valueOf(idStr);
				return false;
			}
		});
	}

	private int delId = 0;

	@Override
	public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) {
		super.onCreateContextMenu(menu, v, menuInfo);
	}

	@Override
	public boolean onContextItemSelected(MenuItem item) {
		if (item.getGroupId() == 1 && item.getItemId() == 1) {
			// 删除Rss
			Log.d(TAG, "delete rss id=" + delId);
			if (RssConst.FAV_ID.equals(String.valueOf(delId))) {
				Toast.makeText(getApplicationContext(), R.string.delValid, Toast.LENGTH_LONG)
						.show();
				return super.onContextItemSelected(item);
			}
			// 删除文章
			itemDb.deleteBySectionId(String.valueOf(delId));
			// 删除RSS
			db.delete(delId);

			Toast.makeText(getApplicationContext(), R.string.delOK, Toast.LENGTH_LONG).show();
			reflushRss();
		} else if (item.getGroupId() == 1 && item.getItemId() == 2) {
			Log.d(TAG, "empty rss id=" + delId);
			// 清空数据
			if (RssConst.FAV_ID.equals(String.valueOf(delId))) {
				Toast.makeText(getApplicationContext(), R.string.delValid, Toast.LENGTH_LONG)
						.show();
				return super.onContextItemSelected(item);
			}
			// 删除文章
			itemDb.deleteBySectionId(String.valueOf(delId));
			reflushRss();
			Toast.makeText(getApplicationContext(), R.string.delOK, Toast.LENGTH_LONG).show();

		}
		return super.onContextItemSelected(item);
	}

	private void reflushRss() {
		List<RssModel> list = loadData();
		rssList.clear();
		rssList.addAll(list);
		adapter.notifyDataSetChanged();
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		menu.add(0, 1, 1, R.string.menu_addRss);
		menu.add(0, 2, 2, R.string.menu_about);
		menu.add(0, 3, 3, R.string.menu_reflush);
		menu.add(0, 4, 4, R.string.menu_backup);
		menu.add(0, 5, 5, R.string.menu_restore);
		menu.add(0, 6, 6, R.string.menu_setting);
		return super.onCreateOptionsMenu(menu);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		if (item.getItemId() == 1) {
			addRssEditText = new EditText(this);
			addRssEditText.setText("http://");
			new AlertDialog.Builder(this).setTitle(R.string.addRssDesc)
											.setIcon(android.R.drawable.ic_dialog_info)
											.setView(addRssEditText)
											.setPositiveButton(R.string.btnOK, new AddRss())
											.setNegativeButton(R.string.btnCancel, null)
											.show();
		} else if (item.getItemId() == 2) {
			Toast.makeText(getApplicationContext(), R.string.app_about, Toast.LENGTH_LONG).show();
		} else if (item.getItemId() == 3) {
			// 刷新所有订阅 Rss
			reflushAllRss();
		} else if (item.getItemId() == 4) {
			// 备份订阅 Rss
			try {
				feedServices.backupRss();
				Toast.makeText(getApplicationContext(), R.string.backupOK, Toast.LENGTH_LONG)
						.show();
			}
			catch (IOException e) {
				e.printStackTrace();
				String msg = ExceptionUtil.exception2String(e);
				LogUtil.d(msg);
				Toast.makeText(getApplicationContext(), R.string.backupERR, Toast.LENGTH_LONG)
						.show();
			}
		} else if (item.getItemId() == 5) {
			// 恢复订阅 Rss
			try {
				boolean b = feedServices.restoreRss();
				reflushRss();
				Toast.makeText(getApplicationContext(), R.string.restoreOK, Toast.LENGTH_LONG)
						.show();
			}
			catch (IOException e) {
				e.printStackTrace();
				String msg = ExceptionUtil.exception2String(e);
				LogUtil.d(msg);
				Toast.makeText(getApplicationContext(), R.string.restoreERR, Toast.LENGTH_LONG)
						.show();
			}
		} else if (item.getItemId() == 6) {
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), SettingActivity.class);

			startActivity(intent);
		}
		return super.onOptionsItemSelected(item);
	}

	// 刷新所有订阅 Rss
	private void reflushAllRss() {
		// 如果网络不可用
		if (!NetUtil.isNetworkAvailable(getApplicationContext())) {
			handler.obtainMessage(MSG_FAILURE).sendToTarget();
			return;
		}
		// 将进度条可见
		progressBar.setVisibility(View.VISIBLE);
		// 初始化线程池
		final ExecutorService executorService = Executors.newFixedThreadPool(5);
		final CompletionService cService = new ExecutorCompletionService(executorService);
		Runnable runnable = new Runnable() {
			@Override
			public void run() {
				List<RssModel> rssModels = loadData();
				for (RssModel model : rssModels) {
					Callable task = new ReflushCallable(model.id);
					cService.submit(task);
				}

				boolean allSuccess = true;
				for (int i = 0; i < rssModels.size(); i++) {
					try {
						RssModel model = (RssModel) cService.take().get();
						//handler.obtainMessage(MODEL_SUCCESS).sendToTarget();
					}
					catch (InterruptedException e1) {
						e1.printStackTrace();
					}
					catch (ExecutionException e1) {
						e1.printStackTrace();
						String msg = ExceptionUtil.exception2String(e1);
						LogUtil.d(msg);
						allSuccess = false;
					}
				}
				// 关闭线程池
				executorService.shutdown();
				if (allSuccess) {
					handler.obtainMessage(MSG_SUCCESS).sendToTarget();
				} else {
					handler.obtainMessage(MSG_FAILURE).sendToTarget();
				}
			}
		};
		Thread thread = new Thread(runnable);
		thread.start();
	}

	private final class ReflushCallable implements Callable {

		private String secetionId;

		/**
		 * @param secetionId
		 */
		public ReflushCallable(String secetionId) {
			super();
			this.secetionId = secetionId;
		}

		/**
		 * Description:
		 * 
		 * @param
		 * @throws
		 * @Author liong Create Date: 2012-4-10 下午4:18:04
		 */
		@Override
		public Object call() throws Exception {
			return feedServices.refrush(secetionId);
		}
	}

	private final class ReflushClickListener implements View.OnClickListener {
		@Override
		public void onClick(View v) {
			reflushAllRss();
		}
	}

	private final class AddRss implements DialogInterface.OnClickListener {
		@Override
		public void onClick(DialogInterface dialog, int which) {
			final String rssUrl = addRssEditText.getText().toString();
			if (rssUrl == null || rssUrl.trim().equals("")) {
				Toast.makeText(	getApplicationContext(),
								R.string.rssUrlCannotNull,
								Toast.LENGTH_LONG).show();
			} else {
				// 将进度条可见
				progressBar.setVisibility(View.VISIBLE);
				Runnable runnable = new Runnable() {
					@Override
					public void run() {
						try {
							feedServices.saveRss(db, rssUrl);
							handler.obtainMessage(ADD_SUCCESS).sendToTarget();
						}
						catch (ParseException e) {
							handler.obtainMessage(ADD_FAILURE).sendToTarget();
						}
						catch (Exception e) {
							handler.obtainMessage(MSG_FAILURE).sendToTarget();
						}
					}
				};
				Thread t = new Thread(runnable);
				t.start();
			}
		}
	}

	public ProgressDialog showDailog() {
		mpDialog = new ProgressDialog(this);
		mpDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);// 设置风格为圆形进度条
		mpDialog.setTitle(R.string.loadingTitle);// 设置标题
		// mpDialog.setIcon(R.drawable.icon);// 设置图标
		mpDialog.setMessage("数据加载中，请稍候...");
		mpDialog.setIndeterminate(false);// 设置进度条是否为不明确
		mpDialog.setCancelable(true);// 设置进度条是否可以按退回键取消
		mpDialog.show();
		return mpDialog;
	}

	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(this).setTitle(R.string.exit)
										.setMessage(R.string.exitMsg)
										.setIcon(android.R.drawable.ic_dialog_info)
										.setPositiveButton(R.string.btnOK, new OnClickListener() {
											@Override
											public void onClick(DialogInterface dialog, int which) {
												// System.exit(0);
												// 完全退出
												String packagename = getPackageName();
												ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
												finish();
												/*
												 * if(getSystemVersion()<8){
												 * 
												 * manager.restartPackage(
												 * getPackageName()); }else{
												 * 
												 * manager.killBackgroundProcesses
												 * (packagename); }
												 */
												manager.killBackgroundProcesses(packagename);
											}
										})
										.setNegativeButton(R.string.btnCancel, null)
										.show();
	}

	private List<RssModel> loadData() {

		return db.findAll();
	}
}